<script lang="ts" setup>
import { ref, unref, useAttrs, watch } from 'vue'
import { SyncOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const emit = defineEmits([
  'update:value',
  'change',
  'blur',
  'input',
  'keydown',
  'pressEnter'
])
const props = defineProps({
  value: { type: String }
})
const guidVal = ref<String>(props.value || '')
const configAttrs = useAttrs()
const defaultAttrs = {
  'allow-clear': true
}
const attrs = { ...defaultAttrs, ...configAttrs }
const inputInstance = ref()

watch(
  (): any => props.value,
  (newVal: String, oldVal) => {
    if (newVal !== oldVal) guidVal.value = newVal
  }
)

const generateGuid = () => {
  const S4 = () =>
    (((1 + Math.random()) * 0x10000) | 0)
      .toString(16)
      .substring(1)
      .toUpperCase()

  return (
    S4() +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    S4() +
    S4()
  )
}

const onGenerate = () => {
  unref(inputInstance).focus()
  guidVal.value = generateGuid()
  emit('update:value', unref(guidVal))
  emit('change', unref(guidVal))
  unref(inputInstance).blur()
}

const onChange = () => {
  emit('update:value', unref(guidVal))
  emit('change', unref(guidVal))
}
const onBlur = () => {
  emit('update:value', unref(guidVal))
  emit('blur')
}
</script>

<template>
  <a-input-group compact style="display: flex">
    <a-input
      ref="inputInstance"
      v-model:value="guidVal"
      v-bind="{ ...attrs }"
      @change="onChange"
      @blur="onBlur"
      @input="e => $emit('input', e)"
      @keydown="e => $emit('keydown', e)"
      @press-enter="(e:Recordable) => $emit('pressEnter', e)"
    />
    <a-tooltip :title="t('component.form.generate')">
      <a-button>
        <template #icon><sync-outlined @click="onGenerate" /></template>
      </a-button>
    </a-tooltip>
  </a-input-group>
</template>